<template>
  <div class="selectTask">
    <div style="display: inline-block">
      任务组：
      <el-select
        v-model="taskGroupValue"
        placeholder="请选择任务组"
        ref="taskGroup"
      >
        <el-option
          v-for="item in taskGroupOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div style="display: inline-block">
      任务：
      <el-select v-model="taskValue" placeholder="请选择任务">
        <el-option
          v-for="item in taskOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      taskGroupOptions: [],
      taskGroupValue: null,
      taskOptions: [],
      taskValue: null,
    };
  },
  props: {
    courseInfo: Object,
  },
  watch: {
    courseInfo(n, o) {
      this.initTaskGroupData();
    },
    taskGroupOptions(n, o) {
      // 自动选择第一个任务组
      if (n.length) {
        this.$nextTick(() => {
          this.$refs.taskGroup.options[0].selectOptionClick();
        });
      }
    },
    taskGroupValue(n, o) {
      this.taskOptions =
        this.taskGroupOptions
          .find((item) => item.taskGroupID == this.taskGroupValue)
          ?.tasks.map((item) =>
            Object.assign(item, { value: item.taskID, label: item.name })
          ) || [];
      this.taskValue = null;
    },
    taskValue(n) {
      if (n) {
        this.$emit("changeTask", this.taskGroupValue, this.taskValue);
      }
    },
  },
  methods: {
    initTaskGroupData() {
      Object.keys(this.courseInfo.taskGroups).forEach((item) => {
        this.taskGroupOptions.push(
          Object.assign(this.courseInfo.taskGroups[item], {
            value: item,
            label: this.courseInfo.taskGroups[item].name,
          })
        );
      });
    },
  },
  mounted() {
    if (this.courseInfo.taskGroups) this.initTaskGroupData();
  },
};
</script>

<style lang="stylus"></style>